<template>
	<view class="messagepage" @click="mainPageClickEven">
		<!-- 消息列表滚动区 -->
		<view
			class="messagescroll"
			:style="{
				backgroundImage: bkPic ? `url(${JSON.stringify(bkPic.url)})` : 'none',
				backgroundSize: 'cover',
				backgroundRepeat: `${bkPic.type}`,
				backgroundPosition: 'center',
				backgroundAttachment: 'fixed',
			
			}"
		>
			<view class="loading-history" v-if="isLoadingHistory">加载历史消息中...</view>
			<view class="no-msg-page" v-if="currentMessages.length === 0">
				<image class="no-msg-img" :src="nomsgurl()" mode=""></image>
			</view>

			<view v-for="(msg, index) in currentMessages" class="message-list" :key="index" :id="`msg-${msg.timestamp}`">
				<!-- 文字消息 和语音-->
				<textMsg
					v-if="msg.messageType === 2 || msg.messageType === 1"
					:msg="msg"
					:lastTimestamp="lastTimestamp(index)"
					:progressPercent="progressPercent"
					:msgList="currentMessages"
					:currentMsg="currentMsg"
				></textMsg>
				<apply-friend v-if="msg.messageType === 7" :msg="msg" @Refresh="Refresh"></apply-friend>
				<!-- 图片消息 -->
				<message-container :lastTimestamp="lastTimestamp(index)" v-if="msg.messageType === 3" :msg="msg" :isCollected="false">
					<image-message :images="msg.content.mediaPath" :msg="msg" />
				</message-container>

				<!-- 视频消息 -->
				<message-container :lastTimestamp="lastTimestamp(index)" v-if="msg.messageType === 6 && msg.content.videoPath" :msg="msg" :isCollected="true">
					<video-message :videoUrl="msg.content.videoPath.videoPath.tempFileURL" :thumbnail="msg.content.videoPath.videoPic.tempFileURL" :msg="msg" />
				</message-container>

				<!-- 商品消息 -->
				<message-container :lastTimestamp="lastTimestamp(index)" v-if="msg.messageType === 4" :msg="msg" :isCollected="true">
					<product-message :msg="msg" />
				</message-container>

				<!-- 店铺消息 -->
				<message-container :lastTimestamp="lastTimestamp(index)" v-if="msg.messageType === 5" :msg="msg" :isCollected="true" @msgUpdata="msgUpdata">
					<store-message :msg="msg" />
				</message-container>
				<message-container :lastTimestamp="lastTimestamp(index)" :isCollect="false" :isReMsg="false" v-if="msg.messageType === 9" :msg="msg">
					<groupinvite :message="msg"></groupinvite>
				</message-container>
				<message-container :lastTimestamp="lastTimestamp(index)" :isCollect="false" :isReMsg="false" v-if="msg.messageType === 8" :msg="msg">
					<location-msg :msg="msg"></location-msg>
				</message-container>
			</view>
			<view class="jump-latest-tip" v-if="currentPage > 1 && !isLoading">已加载历史消息，向下滚动回到最新消息</view>
		</view>

		<linli-input v-if="isFriend"></linli-input>
		<view class="noFriend" @click="toFriend" v-else>还不是好友不能发信息，去加为好友</view>

		<movable-area :style="{ width: systemInfo.windowWidth + 'px', height: systemInfo.windowHeight + 'px', position: 'fixed', left: 0, zIndex: 9999 }">
			<movable-view direction="all" style=" x='500' y='800'">
				<RightBar
					v-if="rightBarShow"
					:favorite-show="true"
					:friend-show="true"
					:bottom="200 + 'rpx'"
					:chat-bar-show="false"
					:cart-show="true"
					:location-tip="true"
					:type="'chat'"
				></RightBar>
			</movable-view>
		</movable-area>
		<chat-title :address="address" @Refresh="Refresh" @backgroudPic="backgroudPic"></chat-title>
		<progressBar></progressBar>
		<notic-bar :top="'130rpx'"></notic-bar>
		<main-botton  :isBtnHidden="isBtnHidden" :customPosition="customPosition"></main-botton>
	</view>
</template>

<script>
// 导入组件
import progressBar from '../../components/progressBar.vue';
import MessageContainer from '../../components/MessageContainer.vue';
import TextMessage from '../../components/message-types/TextMessage.vue';
import ImageMessage from '../../components/message-types/ImageMessage.vue';
import AudioMessage from '../../components/message-types/AudioMessage.vue';
import VideoMessage from '../../components/message-types/VideoMessage.vue';
import ProductMessage from '../../components/message-types/ProductMessage.vue';
import StoreMessage from '../../components/message-types/StoreMessage.vue';
import applyFriend from '../../components/message-types/applyFriend.vue';
import groupinvite from '../../components/message-types/groupinvite.vue';
import * as msgAction from '@/utils/msgAction.js';
import { sendText, voiceMsg, mediaMsg, videoMsg } from '@/methods/msgSend.js';
import textMsg from '../../components/textMsg.vue';
import RightBar from '../../components/RightBar.vue';
import noticBar from '../../components/noticBar.vue';
import avatarGroup from '../../components/avatarGroup.vue';
import chatFromStore from '../../utils/chatFromStore';
import newMsgAction from '../../utils/newMsgAction';
import chatPagination from '../../utils/chatPagination.js';
import chatTitle from '../../components/chatTitle.vue';
import linliInput from '../../components/linliInput.vue';
import locationMsg from '../../components/message-types/locationMsg.vue';
import getFriendUserInfo from '../../utils/getFriendUserInfo';
const friend = uniCloud.importObject('friend', { customUI: true });
import mainBotton from '../../components/mainBotton.vue';
export default {
	components: {
		MessageContainer,
		TextMessage,
		ImageMessage,
		AudioMessage,
		VideoMessage,
		ProductMessage,
		StoreMessage,
		linliInput,
		chatTitle,
		avatarGroup,
		textMsg,
		RightBar,
		progressBar,
		noticBar,
		applyFriend,
		locationMsg,
		groupinvite,
		mainBotton
	},
	data() {
		return {
			rightBarShow: true,
			navBarHeight: 45, // 导航栏高度（px，默认兜底）
			scrollViewHeight: 0, // 消息滚动区高度（px）
			viewId: '', // 滚动目标ID
		
			productMessage: {},
			safeAreaTop: 0,
			windowHeight: 0,
			currentMsg: -1,
			progressPercent: 0,
			//publicMsgReaded: [], // 已读消息ID列表
			poiShow: false,
			markers: [],
			text: '',
			videodata: null,
			systemInfo: {},
			currentPageScrollTop: 0,
			scrollTop: 0,
			isLoadingHistory: false, // 加载历史消息的loading
			isLoadingLatest: false, // 回到最新消息的loading
			lastScrollTop: 0, // 记录上一次滚动位置（判断滚动方向）
			lastScrollHeight: 0,
			unwatch: null,
			messageList: [],
			page: 1,
			hasMore: true,
			pageSize: 20,
			currentId: '',
			queryParam: {
				location: {},
				id: '',
				type: ''
			},
			isFriend: true,
			pagination: null,
			padding: 40,
			isLoading: false,
			bkPic: {},
			userInfoCache: {},
			isBtnHidden: true,
			customPosition: {
				right: '30rpx',
				bottom: '100rpx'
			},
			scrollTimer: null,
			keyHightEvent:false
		};
	},
	computed: {
		storeData() {
			return this.$store.state.msg || {};
		},
	
		currentMessages() {
			const msgs = this.pagination?.currentMessages || [];
			const cache = this.userInfoCache;
			return msgs.map((msg) => {
				const userId = msg.sendUserId;
				if (userId === this.storeData.user.userId) {
					return {
						...msg
					};
				}

				const userInfo = cache[userId] || {};
				return {
					...msg,
					nicName: userInfo.nicName || '匿名',
					nicPic: userInfo.nicPic || ''
				};
			});
		},

		address() {
			return this.$store.state.msg.address || '连接中...';
		},

		currentPage() {
			return this.pagination?.currentPage || 1;
		},
		//TEST：测试用全局变效果
		publicMessageList() {
			return this.$store.state.msg.publicMessageList;
		},
		toTarget() {
			return this.$store.state.msg.toTarget;
		},
		currentTimeMsg() {
			let newMsg = this.$store.state.msg.newMessage || {};
			console.log('+++++', newMsg);
			if (Object.keys(newMsg).length > 0) {
				const isNewMsg = newMsgAction(newMsg, this.queryParam);

				if (isNewMsg.code) {
					return isNewMsg.msg;
				} else {
					return {};
				}
			} else {
				return {};
			}
		},
		cart() {
			return this.$store.state.cart || { items: [] };
		}
	},
	watch: {
		'pagination.currentMessages': {
			handler: async function (newMessages) {
				if (!newMessages || newMessages.length === 0) {
					this.userInfoCache = {};
					return;
				}
				const tempCache = { ...this.userInfoCache };
				const userIdsToFetch = new Set();
				newMessages.forEach((msg) => {
					const userId = msg.sendUserId;
					if (userId && userId !== this.storeData.user.userId && !tempCache[userId]) {
						userIdsToFetch.add(userId);
					}
				});
				if (userIdsToFetch.size > 0) {
					const fetchPromises = Array.from(userIdsToFetch).map((id) => getFriendUserInfo(id));
					const results = await Promise.all(fetchPromises);
					results.forEach((info) => {
						if (info.userId) {
							tempCache[info.userId] = info;
						}
					});
				}
				this.userInfoCache = tempCache;
			},
			immediate: true,
			deep: true
		}
	},

	mounted() {
		this.getSystemInfo();
		// 3. 监听子组件图片消息事件
		uni.$on('keyHightEvent', (res) => {
			this.keyHightEvent=res
			if (res) {
				this.bottomHeight = '230px';
				this.isBtnHidden=true
				this.scrollToLast()
			} else {
				this.isBtnHidden=false
				this.bottomHeight = '0px';
			}
		});
		uni.$on('viewId', (res) => {
			this.viewId = res;
		});
		uni.$on('currentMsg', (res) => {
			this.currentMsg = res;
		});
		uni.$on('progressPercent', (res) => {
			this.progressPercent = res;
		});
	},
	onPageScroll(e) {
		this.currentPageScrollTop = e.scrollTop;
		if (!this.isBtnHidden) {
			this.isBtnHidden = true;
		}

		if (this.scrollTimer) {
			clearTimeout(this.scrollTimer);
			this.scrollTimer = null;
		}
		this.scrollTimer = setTimeout(() => {
			if(!this.keyHightEvent){
				this.isBtnHidden = false;	
			}
		
		}, 300);

		if (e.scrollTop === 0 && !this.isLoadingHistory && this.hasMore) {
			this.loadHistoryMessages(e); // 加载历史消息
		}
	},
	beforeDestroy() {
		uni.$off('viewId');
		uni.$off('currentMsg');
		uni.$off('progressPercent');
		this.unwatch = () => {
			watchNewMsg();
		};
		if (this.scrollTimer) {
			clearTimeout(this.scrollTimer);
			this.scrollTimer = null;
		}
	},

	onLoad(res) {
		this.bkPic = uni.getStorageSync('backPic') || {};
		this.pagination = new chatPagination([], 15);
		this.watchAction();
	},

	async onShow() {
		this.initData();
		console.log('.....', this.toTarget);
		// const res=await linli.doubao(this.storeData.location)
		//console.log(res);
	},
	onHide() {},
	methods: {
		backgroudPic(e) {
			this.bkPic = e;
		},
		async getIsFriend(params) {
			if (params.type === 'person') {
				try {
					const res = await friend.isFriend({ userId: this.storeData.user.userId, targetUserId: params.id });
					if (res.success) {
						this.isFriend = res.data.isFriend;
					}
				} catch (e) {
					console.error(e);
				}
			}
		},
		toFriend() {
			uni.navigateTo({
				url: `/pages/friend/friend?id=${this.queryParam.id}`
			});
		},

		Refresh() {
			this.initData();
		},
		async initData() {
			this.$store.commit('msg/SET_publicMessageList', []);
			this.queryParam = this.$store.state.msg.queryParam;
			this.getIsFriend(this.queryParam);
			// 1. 初始化分页实例（避免重复创建）
			if (!this.pagination) {
				this.pagination = new chatPagination([], 15);
			}
			if (this.queryParam.type === 'stranger') return;
			setTimeout(async () => {
				try {
					const viewlist = await chatFromStore(this.queryParam, this.storeData.user);

					this.$store.commit('msg/SET_publicMessageList', viewlist); //测试
					await this.pagination.resetWithNewMessages(viewlist);
					await this.$nextTick();

					this.scrollToLast();
				} catch (e) {
					console.error('加载消息失败：', e);
					uni.showToast({ title: '加载消息失败', icon: 'fail' });
				}
			}, 0);
		},
		watchAction() {
			// 1. 单独监听 currentTimeMsg（处理新消息）
			const watchNewMsg = this.$watch(
				() => this.currentTimeMsg, // 只监听新消息变化
				(newTimeMsg) => {
					console.log('有新消息吗', newTimeMsg);
					if (!newTimeMsg || Object.keys(newTimeMsg).length === 0) return;

					const index = this.publicMessageList.findIndex((item) => item.timestamp === newTimeMsg.timestamp); //测试

					if (index == -1) {
						const messageList = [...this.publicMessageList, newTimeMsg]; //测试
						this.$store.commit('msg/SET_publicMessageList', messageList); //测试全局
						this.pagination.resetWithNewMessages(this.publicMessageList);
					} else {
						const newList = this.publicMessageList; //测试
						newList[index] = newTimeMsg;
						this.$store.commit('msg/SET_publicMessageList', [...newList]); //测试
						this.pagination.resetWithNewMessages(this.publicMessageList);
					}
					this.scrollToLast(); //测试全局
				},
				{ deep: true, immediate: false } // 不立即执行，仅新消息变化时触发
			);
		},
		// 获取系统信息（窗口高度+导航栏实际高度）

		navigateBack() {
			uni.navigateBack();
		},
		nomsgurl() {
			// 生成 0-3 的整数索引（避免出现 0.xxx 非整数路径）
			const index = Math.floor(Math.random() * 4);
			// 兼容 H5/小程序/App 路径，建议用绝对路径（@ 指向根目录）
			return `/static/nomsg/${index}.png`;
		},
		scrollToLast(retryCount = 0) {
			const MAX_RETRY = 3;
			if (retryCount > MAX_RETRY) {
				console.warn('超过最大重试次数，未找到消息DOM');
				return;
			}

			if (!this.currentMessages || this.currentMessages.length === 0) {
				console.warn('没有消息可滚动');
				return;
			}

			const lastMsg = this.currentMessages[this.currentMessages.length - 1];
			const msgId = `msg-${lastMsg.timestamp}`;

			this.$nextTick(() => {
				uni.createSelectorQuery()
					.in(this)
					.select(`#${msgId}`)
					.boundingClientRect((msgRect) => {
						if (msgRect) {
							console.warn('找到DOM', msgId);
							const currentScrollTop = this.currentPageScrollTop;
							const targetScrollTop = currentScrollTop + msgRect.top;
							uni.pageScrollTo({
								scrollTop: Math.max(0, targetScrollTop), // 确保不小于0
								duration: 0,
								fail: (err) => {
									console.error('滚动失败：', err);
								}
							});
						} else {
							setTimeout(() => {
								this.scrollToLast(retryCount + 1);
							}, 100);
						}

						// 直接使用 onPageScroll 中记录的当前滚动距离
					})
					.exec();
			});
		},
		//监听消息滚动
		getSystemInfo() {
			this.systemInfo = this.storeData.systemInfo;
			this.safeAreaTop = this.systemInfo.safeArea.top;
			this.windowHeight = this.systemInfo.windowHeight;
		},

		// 滚动到目标元素的核心方法
		async loadHistoryMessages(e) {
			// 防抖动处理
			if (this.isLoadingHistory) return;
			this.isLoadingHistory = true;

			try {
				if (!this.hasMore) {
					uni.showToast({ title: '已加载全部历史消息', icon: 'none' });
					return;
				}

				// 显示加载中提示
				uni.showLoading({ title: '加载中...', mask: false });
				const query = uni.createSelectorQuery().in(this);
				// 并行获取初始高度和当前滚动位置（假设 currentScrollTop 由 onPageScroll 实时更新）
				const [initialRect] = await Promise.all([new Promise((resolve) => query.select('.messagescroll').boundingClientRect(resolve).exec())]);

				// 初始高度容错
				if (!initialRect || typeof initialRect.height !== 'number') {
					console.warn('无法获取消息容器初始高度');
					return;
				}
				const initialHeight = initialRect.height;
				const currentPageScrollTop = this.currentPageScrollTop; // 从 data 中获取实时滚动位置

				// 加载更多历史消息
				const hasMore = await this.pagination.loadMoreHistory();
				this.hasMore = hasMore;

				// 等待 DOM 更新
				await this.$nextTick();

				setTimeout(async () => {
					const newRect = await new Promise((resolve) => query.select('.messagescroll').boundingClientRect(resolve).exec());
					if (!newRect || typeof newRect.height !== 'number') {
						console.warn('无法获取消息容器新高度');
						return;
					}
					console.log('旧高度', initialHeight, '新高度', newRect.height, '原始位置', currentPageScrollTop);
					// 计算高度差并调整滚动位置
					const delta = newRect.height - initialHeight;
					if (delta > 0 && currentPageScrollTop !== null) {
						// 原滚动位置 + 新增高度 = 保持视觉位置不变
						const newScrollTop = currentPageScrollTop + delta;
						console.log('跑动多少位置 ', newScrollTop);
						uni.pageScrollTo({
							scrollTop: newScrollTop,
							duration: 0
						});
					}
				}, 300);
			} catch (e) {
				console.error('加载历史消息失败：', e);
				uni.showToast({ title: '加载失败，请重试', icon: 'none' });
			} finally {
				this.isLoadingHistory = false;
				uni.hideLoading(); // 关闭加载提示
			}
		},
		sendmsg(msg) {
			console.log('11111', msg);
			if (msg.msg) {
				// 1. 合并新消息到 messageList
				//TEST：测试全局
				const newMessageList = [...this.publicMessageList, msg.msg]; //测试
				this.$store.commit('msg/SET_publicMessageList', newMessageList); //测试
				this.messageList = newMessageList;
				// const newMessageList = [...this.messageList, msg.msg];测试
				// this.messageList = newMessageList;测试
				// 2. 调用 pagination 的 reset 方法更新（而非直接操作 currentMessages）
				this.pagination.resetWithNewMessages(newMessageList);
				// 3. 跳转到最新消息（可选，发送新消息后默认滚动到底部）
				this.pagination.jumpToLatest();
				this.scrollToLast();
			}

			// 视频消息逻辑保留
			if (msg.type === 'video') {
				this.$refs.popup.open();
				this.videodata = msg.msg;
			}
		},

		lastTimestamp(index) {
			if (index > 0) {
				return this.currentMessages[index - 1].timestamp;
			} else {
				return 0;
			}
		},

		// 主页面点击：关闭输入框/键盘
		mainPageClickEven() {
			//uni.hideKeyboard();
			uni.$emit('mainPageClickEven'); // 通知子组件关闭输入状态
		},

		// 跳转到购物车
		toCart() {
			uni.navigateTo({ url: '/pages/shopcart/shopcart' });
		},

		// 店铺消息更新回调（子组件触发）
		msgUpdata() {
			console.log('店铺消息已更新');
			// 可添加刷新消息列表逻辑（如重新拉取数据）
		}
	}
};
</script>

<style lang="scss" scoped>
.messagepage {
	width: 100vw;
	min-height: 100vh;
	background-color: #f0f0f0;
}
.messagescroll {
	padding-top: 202rpx;
	width: 100%; // 确保宽度占满
	min-height: calc(100vh - 280rpx); // 减去顶部padding，占满剩余高度
	overflow-y: auto; // 保留滚动功能
	padding-bottom: 100rpx;
}
.noFriend {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
	width: 100%;
	height: 80rpx;
	background-color: #4a95df;
	color: #fff;
	display: flex;
	justify-content: center;
	align-items: center;
}
/* 购物车悬浮按钮 */
.cart {
	position: fixed;
	right: 50rpx;
	z-index: 99;
	width: 100rpx;
	height: 100rpx;
	border-radius: 50%;
	transition: bottom 0.2s ease; /* 平滑过渡 */
}
.cart_img {
	height: 100%;
	width: 100%;
	position: relative;
}
.cart_bot {
	position: absolute;
	top: 5rpx;
	right: 5rpx;
	width: 30rpx;
	height: 30rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #ff3b30;
	border-radius: 50%;
	padding: 5rpx;
	z-index: 9999;
}
.title {
	display: flex;
	height: 130rpx;
	width: 750rpx;
	position: fixed;
	color: #fff;
	font-weight: 700;
	top: 0;
	left: 0;
	right: 0;
	z-index: 100;
	padding: 30rpx;
	background-color: #4a95df;
	.title-content {
		display: flex;
		width: 100%;
		margin-bottom: 0;
		margin-top: auto;
	}
	.title-mid {
		font-size: 28rpx;
		margin-left: 25rpx;
	}
	.tille-right {
		padding-left: 50rpx;
		margin-right: 80rpx;
		margin-left: auto;
	}
}
.loading-history {
	text-align: center;
	color: #999;
	font-size: 24rpx;
	padding: 10rpx 0;
}

/* 回到最新消息提示 */
.jump-latest-tip {
	text-align: center;
	color: #4a95df;
	font-size: 24rpx;
	padding: 10rpx 0;
	background: rgba(255, 255, 255, 0.8);
	border-radius: 30rpx;
	margin: 20rpx auto;
	width: 600rpx;
}

/* 修复 message-list 样式（确保只有一个父容器，避免滚动异常） */
.message-list {
	display: flex;

	flex-direction: column;
	gap: 10rpx;
	//background-color: #f0f0f0;
}
.no-msg-page {
	width: 400rpx;
	height: 400rpx;
	margin: 0 auto;
	margin-top: 50%;
	border-radius: 20rpx;
	display: flex;
	flex-direction: column; // 垂直排列图片和文字
	justify-content: center;
	align-items: center;
}

.no-msg-img {
	width: 400rpx;
	height: 400rpx;
	border-radius: 20rpx;
	margin-bottom: 20px;
	object-fit: contain;
}

.no-msg-text {
	font-size: 18px;
	color: #666;
}
</style>
